package com.obook.bln;

import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.obook.epdhelper.EPDHelper;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    BLNCommand mCommand;

    Button btnRed;
    Button btnGreen;
    Button btnMotor;
    Button btnSetRefreshMode;
    Button btnSetGu16Limit;
    Button btnForceGlobalRefresh;
    Button btnTest1;
    Button btnWakeUp;

    boolean isAutoWakeup = false;

    BroadcastReceiver receiver;

    private static final String ACTION_WAKEUP = "com.obook.wakeup.ACTION_WAKEUP";

    private static final int SLEEP_TIMEOUT = 3000; // 3s之后 进入休眠
    private static final int WAKEUP_TIMEOUT = 10000; // 10s 之后进入唤醒

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCommand = new BLNCommand();

        btnRed = findViewById(R.id.btn_red);
        btnGreen = findViewById(R.id.btn_green);
        btnMotor = findViewById(R.id.btn_motor);
        btnSetRefreshMode = findViewById(R.id.setRefreshMode);
        btnSetGu16Limit = findViewById(R.id.setGu16Limit);
        btnForceGlobalRefresh = findViewById(R.id.forceGlobalRefresh);
        btnTest1 = findViewById(R.id.gototest1);
        btnWakeUp = findViewById(R.id.btn_wakeup);

        btnRed.setOnClickListener(this);
        btnGreen.setOnClickListener(this);
        btnMotor.setOnClickListener(this);
        btnSetRefreshMode.setOnClickListener(this);
        btnSetGu16Limit.setOnClickListener(this);
        btnForceGlobalRefresh.setOnClickListener(this);
        btnTest1.setOnClickListener(this);
        btnWakeUp.setOnClickListener(this);

        receiver = new ScreenChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_WAKEUP);
        registerReceiver(receiver, filter);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 这里窗体实际上并未获得焦点
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus)
            EPDHelper.getInstance().forceGLobalRefresh(getWindow(), true);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    public void toggleMotor() {
        mCommand.exec(BLNCommand.CMD_OPEN_MATOR);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mCommand.exec(BLNCommand.CMD_CLOSE_MATOR);
    }

    public void toggleGreen() {
        mCommand.exec(String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, BLNCommand.MAX_BRIGHTNESS));

        mCommand.exec(BLNCommand.CMD_OPEN_GREEN);

        int bright = BLNCommand.MAX_BRIGHTNESS;

        while (bright >= BLNCommand.MIN_BRIGHTNESS) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mCommand.exec(String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, bright));
            bright-=5;
        }

        while (bright <= BLNCommand.MAX_BRIGHTNESS) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mCommand.exec(String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, bright));
            bright+=5;
        }

        mCommand.exec(BLNCommand.CMD_CLOSE_GREEN);
    }

    public void toggleRed() {
        mCommand.exec(String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, BLNCommand.MAX_BRIGHTNESS));

        mCommand.exec(BLNCommand.CMD_OPEN_RED);

        int bright = BLNCommand.MAX_BRIGHTNESS;

        while (bright >= BLNCommand.MIN_BRIGHTNESS) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String str = String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, bright);
            mCommand.exec(str);
            bright-=5;
        }

        while (bright <= BLNCommand.MAX_BRIGHTNESS) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String str = String.format(BLNCommand.CMD_CHANGE_BRIGHTNESS_PATTERN, bright);
            mCommand.exec(str);
            bright+=5;
        }

        mCommand.exec(BLNCommand.CMD_CLOSE_RED);
    }

    int count_mode = 0;
    int count_limit = 0;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_green:
                toggleGreen();
                break;
            case R.id.btn_red:
                toggleRed();
                break;
            case R.id.btn_motor:
                toggleMotor();
                break;
            case R.id.setRefreshMode:
                count_mode++;
                EPDHelper.Mode value = EPDHelper.Mode.values()[count_mode % EPDHelper.Mode.values().length];
                Log.d(TAG, "onClick: mode = " + value.name());
                EPDHelper.getInstance().setRefreshMode(getWindow(), value);
                break;
            case R.id.setGu16Limit:
                count_limit++;
                Log.d(TAG, "onClick: count_limit = " + count_limit);
                EPDHelper.getInstance().setGu16RefreshLimit(getWindow(), count_limit % 20);
                break;
            case R.id.forceGlobalRefresh:
                EPDHelper.getInstance().forceGLobalRefresh(getWindow(), true);
                break;
            case R.id.gototest1:
                Intent intent_test1 = new Intent(this, GC16Activity.class);
                startActivity(intent_test1);
            case R.id.btn_wakeup:
                Log.d(TAG, "onClick: btn_wakup");
                isAutoWakeup = !isAutoWakeup;
                btnWakeUp.setText("定时唤醒 " + (isAutoWakeup ? "true" : "false"));
                break;
        }
    }

    class ScreenChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                Log.d(TAG, "onReceive: ACTION_SCREEN_ON");
//                toggleMotor();
                int count = 0;
                while (count < 3) {
                    toggleRed();
                    count++;
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
//                toggleMotor();
                Log.d(TAG, "onReceive: ACTION_SCREEN_OFF");
                int count = 0;
                while (count < 3) {
                    toggleGreen();
                    count++;
                }

                // 设置唤醒时间
                if (isAutoWakeup)
                    setAlarm(WAKEUP_TIMEOUT);
            } else if (ACTION_WAKEUP.equals(action)) {
                Log.d(TAG, "onReceive: ACTION_WAKEUP");
                turnOnScreen(MainActivity.this);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void setAlarm(long time_ms) {
        Log.d(TAG, "setAlarm: ");
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_WAKEUP), 0);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time_ms + System.currentTimeMillis(), pendingIntent);
    }

    private void setScreenOffTime(Context context, int time_ms) {
        Log.d(TAG, "setScreenOffTime: ");
        Settings.System.putInt(context.getContentResolver(), "screen_off_timeout", time_ms);
    }


    private void turnOnScreen(Context context) {
        PowerManager pw = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pw != null) {
            pw.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                    "factoryTest:ScreenOnTimer").acquire(SLEEP_TIMEOUT);
        }
    }
}
